<%@ page import="java.sql.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<%
try {
String connectionURL = "jdbc:mysql://webproject2.cse.ust.hk/BookwarmMobile?user=BookwarmMobile&password=bookwarm";

Connection connection = null;

Class.forName("com.mysql.jdbc.Driver").newInstance();

connection = DriverManager.getConnection(connectionURL);

if(!connection.isClosed()) {
String newISBN = null;
String newAccountName = null;

newISBN = request.getParameter("isbn");
newAccountName = request.getParameter("username");

int count_listed = 0;
Statement statement0 = null;
ResultSet rs0 = null;
statement0 = connection.createStatement();
String query0 = "SELECT count(*) AS Count FROM WishList WHERE AccountName ='" + newAccountName + "' AND ISBN = '" + newISBN + "' AND Status = 'Listed';";
out.print(query0);
rs0 = statement0.executeQuery(query0);
if(rs0.next()) {
count_listed = Integer.parseInt(rs0.getString("Count"));

}

if(count_listed != 0) {
int count_record = 0;
Statement statement1 = null;
statement1 = connection.createStatement();
String query1 = "UPDATE WishList SET TransDate = CURRENT_TIMESTAMP WHERE AccountName = '" + newAccountName + "' AND ISBN = '" + newISBN + "' AND Status = 'Listed';";
count_record = statement1.executeUpdate(query1, Statement.NO_GENERATED_KEYS);
statement1.close();

if(count_record != 0) {
out.print("insert_successful");

}
else {
out.print("insert_failed");

}

}
else {
int count_record = 0;
Statement statement2 = null;
statement2 = connection.createStatement();
String query2 = "INSERT INTO WishList VALUES (DEFAULT, '" + newAccountName + "', '" + newISBN + "', DEFAULT, DEFAULT);";
count_record = statement2.executeUpdate(query2, Statement.NO_GENERATED_KEYS);
statement2.close();

if(count_record != 0) {
out.print("insert_successful");

}
else {
out.print("insert_failed");

}

}

}

connection.close();

}
catch(Exception ex){
out.print(ex);

}
%>